import os
import time

import requests
import datetime
import bs4
import json


def open_url(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    res = requests.get(url, headers=headers)
    return res


def getmidstring(html, start_str, end):
    start = html.find(start_str)
    if start >= 0:
        start += len(start_str)
        end = html.find(end, start)
        if end >= 0:
            return html[start:end].strip()


def getSelectLink(selectWord):
    res = open_url(
        f"https://weixin.sogou.com/weixin?type=2&s_from=input&query={selectWord}&ie=utf8&_sug_=n&_sug_type_=")
    html = bs4.BeautifulSoup(res.text, "html.parser")
    titleList = html.find_all("div", class_="txt-box")
    for item in titleList:
        if item.h3.a.get_text() == selectWord:
            return "https://weixin.sogou.com" + item.h3.a["href"]
    return ""


def sendMessage(title, message):
    url = "https://sc.ftqq.com/SCU95883T9d3eccc99f6b4ef72e93f1fc8bc698735ea82df776916.send"
    params = {
        'text': str(title),
        'desp': str(message)
    }
    try:
        res = requests.post(url, data=params)
    except Exception:
        return False
    if json.loads(res.text)["errmsg"] == "success":
        return True
    else:
        print("错误：" + json.loads(res.text)["errmsg"])
        return False


def getURLMessage(text):
    html = bs4.BeautifulSoup(text, "html.parser")
    mainText = html.find_all("section", act="xmy")
    messages = str(mainText[0].get_text()).split("。")
    message = ""
    for item in messages:
        if "日" not in item:
            continue
        item = item.replace("更多资讯-请关注典通APP ", "")
        item = item.replace("专业生产经营龙门剪、虎头剪，鳄鱼剪，钢筋带外刀颗粒机，金属压块机、废纸打包机等各类液压设备，可根据客户需求定制生产 ", "")
        message = message + "\n\n" + item
    return message


def main():
    ConfigFile = os.path.dirname(__file__) + os.path.basename(__file__).split(".")[0] + ".ini"
    if not os.path.exists(ConfigFile):
        with open(ConfigFile, "w", encoding="utf8") as f:
            f.write("")
    while True:
        NowDate = datetime.datetime.now().date()
        try:
            f = open(ConfigFile, "r", encoding="utf8")
            if str(NowDate) in f.read():
                print("检测到今日已推送信息，两小时后继续")
                time.sleep(3600 * 2)
                continue
        except Exception:
            pass
        NowMonth = datetime.datetime.now().month
        NowDay = datetime.datetime.now().day

        # selectWord = str(NowMonth) + "月" + str(NowDay) + "日废钢行情汇总"
        selectWord = str(NowMonth) + "月" + "14" + "日废钢行情汇总"
        URL = getSelectLink(selectWord)
        if URL == "":
            URL = getSelectLink(selectWord.replace("汇总", ""))
            if URL == "":
                print("未获取到今日行情，十分钟后继续")
                time.sleep(600)
                continue
        print(f"查询链接：{URL}")

        # 获取实际链接

        # 打开实际链接
        # res = open_url(URL)
        # 解析数据
        # message = getURLMessage(res.text)
        if not sendMessage("今日废钢详情 - " + str(datetime.datetime.now().date()), URL):
            print("信息推送失败，十分钟后继续")
            time.sleep(600)
            continue
        print("信息推送成功")
        try:
            f = open(ConfigFile, "r+", encoding="utf8")
            f.write(f.read() + "\n" + str(NowDate))
            f.close()
        except Exception:
            print("文件保存失败，正在采取尝试修复")
            if not os.path.exists(ConfigFile):
                with open(ConfigFile, "w", encoding="utf8") as f:
                    f.write(str(NowDate))


if __name__ == "__main__":
    main()
